package com.elong.qadev.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.elong.qadev.entity.CaseNode;
import com.elong.qadev.entity.Entities;
import com.elong.qadev.entity.Header;
import com.elong.qadev.entity.HttpCase;
import com.elong.qadev.entity.NameValuePair;
import com.elong.qadev.entity.RunAfter;
import com.elong.qadev.entity.RunBefore;
import com.elong.qadev.entity.UrlParam;
import com.elong.qadev.entity.User;
import com.elong.qadev.run.RunClient;
import com.elong.qadev.service.CaseServiceI;
import com.elong.qadev.service.HttpCaseServiceI;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @ClassName: HttpCaseAction
 * @Description: TODO(存放接口测试用例相关前台业务操作)
 * @author kangchen
 * @date 2015年9月8日
 *
 */
@ParentPackage("all")
public class HttpCaseAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(HttpCaseAction.class);
	@Autowired
	private HttpCaseServiceI httpCaseService;
	@Autowired
	protected CaseServiceI caseService;
	public String[] getRunBefore() {
		return runBefore;
	}

	public void setRunBefore(String[] runBefore) {
		this.runBefore = runBefore;
	}

	public String[] getRunAfter() {
		return runAfter;
	}

	public void setRunAfter(String[] runAfter) {
		this.runAfter = runAfter;
	}

	private String[] headers;
	private String[] urlParams;
	private String[] nameValuePairs;
	private String[] runBefore;
	private String[] runAfter;
	private Entities entities;
	private HttpCase httpCase;
	private String caseId;

	public String getCaseId() {
		return caseId;
	}

	public void setCaseId(String caseId) {
		this.caseId = caseId;
	}

	public String[] getHeaders() {
		return headers;
	}

	public void setHeaders(String[] headers) {
		this.headers = headers;
	}

	public String[] getUrlParams() {
		return urlParams;
	}

	public void setUrlParams(String[] urlParams) {
		this.urlParams = urlParams;
	}

	public String[] getNameValuePairs() {
		return nameValuePairs;
	}

	public void setNameValuePairs(String[] nameValuePairs) {
		this.nameValuePairs = nameValuePairs;
	}

	public Entities getEntities() {
		return entities;
	}

	public void setEntities(Entities entities) {
		this.entities = entities;
	}

	public HttpCase getHttpCase() {
		return httpCase;
	}

	public void setHttpCase(HttpCase httpCase) {
		this.httpCase = httpCase;
	}
	/**
	 * 
	* @Title: httpCaseSave
	* @Description: TODO(保存创建或编辑的HTTP用例数据)
	* @param     参数
	* @return void    返回类型
	* @throws
	 */
	@Action(value = "httpCaseSave")
	public void httpCaseSave() {
		HttpCase httpCaseOld = httpCaseService.getHttpCase(Integer
				.parseInt(caseId));
		if (httpCaseOld != null) {
			Date oldDate = httpCaseOld.getCreateDateTime();
			boolean isDelete = httpCaseService.deleteAllCaseInfo(Integer
					.parseInt(caseId));
			if (isDelete)
				logger.info("保存前，用例数据删除成功，提取创建时间："+oldDate);
			httpCase.setCreateDateTime(oldDate);
			httpCase.setOwer(httpCaseOld.getOwer());
		}else{
			httpCase.setCreateDateTime(new Date());
			User u = (User) ActionContext.getContext().getSession().get("user");
			httpCase.setOwer(u.getName());
		}

		logger.info("获取到得caseId信息是:" + caseId);
		logger.info("获取到得httpCase信息是:" + httpCase.toString());
		logger.info("获取到得headers信息是:" + Arrays.toString(headers));
		logger.info("获取到得urlParams信息是:" + Arrays.toString(urlParams));
		logger.info("获取到得nameValuePairs信息是:" + Arrays.toString(nameValuePairs));
		logger.info("获取到得runBefore信息是:" + Arrays.toString(runBefore));
		logger.info("获取到得runAfter信息是:" + Arrays.toString(runAfter));
		logger.info("获取到得entities信息是:" + entities.toString().length());

		ArrayList<Header> lh = new ArrayList<Header>();
		int lhi = 0;
		for (int i = 0; i < headers.length; i++) {
			if (headers[i].equals("")) {
				i++;
				continue;
			}
			Header h = new Header();
			h.setCaseId(Integer.parseInt(caseId));
			h.setKey(headers[i]);
			h.setValue(headers[++i]);
			logger.info("将要存储的header信息是:" + h.toString());
			logger.info("数组序列号是:" + lhi);
			lh.add(lhi++, h);
		}
		if (null != lh){			
			Collections.reverse(lh);
			logger.info("Header数据存储结果为："
					+ (!(httpCaseService.saveHeaders(lh)) ? false : true));
		}

		ArrayList<UrlParam> lu = new ArrayList<UrlParam>();
		int lui = 0;
		for (int i = 0; i < urlParams.length; i++) {
			if (urlParams[i].equals("")) {
				i++;
				continue;
			}
			UrlParam h = new UrlParam();
			h.setCaseId(Integer.parseInt(caseId));
			h.setKey(urlParams[i]);
			h.setValue(urlParams[++i]);
			lu.add(lui++, h);
		}

		if (null != lu){
			Collections.reverse(lu);
			logger.info("UrlParam数据存储结果为："
					+ (!(httpCaseService.saveUrlParams(lu)) ? false : true));
		}

		ArrayList<NameValuePair> ln = new ArrayList<NameValuePair>();
		int lni = 0;
		for (int i = 0; i < nameValuePairs.length; i++) {
			if (nameValuePairs[i].equals("")) {
				i++;
				continue;
			}
			NameValuePair h = new NameValuePair();
			h.setCaseId(Integer.parseInt(caseId));
			h.setKey(nameValuePairs[i]);
			h.setValue(nameValuePairs[++i]);
			ln.add(lni++, h);
		}

		if (null != ln){
			Collections.reverse(ln);
			logger.info("UrlParam数据存储结果为："
					+ (!(httpCaseService.saveNameValuePairs(ln)) ? false : true));
		}

		if (entities != null) {
			entities.setCaseId(Integer.parseInt(caseId));
			httpCaseService.saveEntities(entities);
		}
		if (httpCase != null) {
			httpCase.setCaseId(Integer.parseInt(caseId));
			httpCase.setCaseType("FLIGHT/ORDER");
			httpCase.setModifyDateTime(new Date());
			httpCaseService.saveHttpCase(httpCase);
		}

		if (runBefore != null) {
			ArrayList<RunBefore> lb = new ArrayList<RunBefore>();
			int lbi = 0;
			for (int i = 0; i < runBefore.length; i++) {
				if (runBefore[i].equals("")||runBefore[i].equals("请选择相应方法分类")) {
					i += 2;
					continue;
				}
				RunBefore h = new RunBefore();
				h.setCaseId(Integer.parseInt(caseId));
				h.setClassPath(runBefore[i]);
				h.setBeforeMethod(runBefore[++i]);
				h.setBeforeMethodArgs(runBefore[++i]);
				lb.add(lbi++, h);
			}
			if (null != lb){
				Collections.reverse(lb);
				logger.info("runBefore数据存储结果为："
						+ (!(httpCaseService.saveRunBefores(lb)) ? false : true));
			}
		}

		if (runAfter != null) {
			ArrayList<RunAfter> lr = new ArrayList<RunAfter>();
			int lri = 0;
			for (int i = 0; i < runAfter.length; i++) {
				if (runAfter[i].equals("")||runAfter[i].equals("请选择相应方法分类")) {
					i += 2;
					continue;
				}
				RunAfter h = new RunAfter();
				h.setCaseId(Integer.parseInt(caseId));
				h.setClassPath(runAfter[i]);
				h.setAfterMethod(runAfter[++i]);
				h.setAfterMethodArgs(runAfter[++i]);
				lr.add(lri++, h);
			}

			if (null != lr){
				Collections.reverse(lr);
				logger.info("runAfter数据存储结果为："
						+ (!(httpCaseService.saveRunAfters(lr)) ? false : true));
			}
		}

		String msg = "保存成功";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(msg);
		out.flush();
		out.close();
	}
	/**
	 * 
	* @Title: httpCaseSend
	* @Description: TODO(执行HTTP用例发送执行操作)
	* @param     参数
	* @return void    返回类型
	* @throws
	 */
	@Action(value = "httpCaseSend")
	public void httpCaseSend() {
		
		logger.info("获取到得httpCase信息是:" + httpCase.toString());
		logger.info("获取到得headers信息是:" + Arrays.toString(headers));
		logger.info("获取到得urlParams信息是:" + Arrays.toString(urlParams));
		logger.info("获取到得nameValuePairs信息是:" + Arrays.toString(nameValuePairs));
		logger.info("获取到得runBefore信息是:" + Arrays.toString(runBefore));
		logger.info("获取到得runAfter信息是:" + Arrays.toString(runAfter));
		logger.info("获取到得entities信息是:" + entities.toString());

		ArrayList<Header> lh = new ArrayList<Header>();
		ArrayList<UrlParam> lu = new ArrayList<UrlParam>();
		ArrayList<NameValuePair> ln = new ArrayList<NameValuePair>();
		ArrayList<RunBefore> lb = new ArrayList<RunBefore>();
		ArrayList<RunAfter> lr = new ArrayList<RunAfter>();
		//entities
		//httpCase
		
		int lhi = 0;
		for (int i = 0; i < headers.length; i++) {
			if (headers[i].equals("")) {
				i++;
				continue;
			}
			Header h = new Header();
			h.setCaseId(Integer.parseInt(caseId));
			h.setKey(headers[i]);
			h.setValue(headers[++i]);
			logger.info("将要存储的header信息是:" + h.toString());
			logger.info("数组序列号是:" + lhi);
			lh.add(lhi++, h);
		}		

		int lui = 0;
		for (int i = 0; i < urlParams.length; i++) {
			if (urlParams[i].equals("")) {
				i++;
				continue;
			}
			UrlParam h = new UrlParam();
			h.setCaseId(Integer.parseInt(caseId));
			h.setKey(urlParams[i]);
			h.setValue(urlParams[++i]);
			lu.add(lui++, h);
		}

		int lni = 0;
		for (int i = 0; i < nameValuePairs.length; i++) {
			if (nameValuePairs[i].equals("")) {
				i++;
				continue;
			}
			NameValuePair h = new NameValuePair();
			h.setCaseId(Integer.parseInt(caseId));
			h.setKey(nameValuePairs[i]);
			h.setValue(nameValuePairs[++i]);
			ln.add(lni++, h);
		}

		if (runBefore != null) {
			int lbi = 0;
			for (int i = 0; i < runBefore.length; i++) {
				if (runBefore[i].equals("")) {
					i += 2;
					continue;
				}
				RunBefore h = new RunBefore();
				h.setCaseId(Integer.parseInt(caseId));
				h.setClassPath(runBefore[i]);
				h.setBeforeMethod(runBefore[++i]);
				h.setBeforeMethodArgs(runBefore[++i]);
				lb.add(lbi++, h);
			}
		}

		if (runAfter != null) {
			int lri = 0;
			for (int i = 0; i < runAfter.length; i++) {
				if (runAfter[i].equals("")) {
					i += 2;
					continue;
				}
				RunAfter h = new RunAfter();
				h.setCaseId(Integer.parseInt(caseId));
				h.setClassPath(runAfter[i]);
				h.setAfterMethod(runAfter[++i]);
				h.setAfterMethodArgs(runAfter[++i]);
				lr.add(lri++, h);
			}
		}
		httpCase.setCaseId(Integer.parseInt(caseId));
		entities.setCaseId(Integer.parseInt(caseId));
		
		Map<String,Object> content = new HashMap<String,Object>();
		Collections.reverse(lh);
		Collections.reverse(lu);
		Collections.reverse(ln);
		Collections.reverse(lb);
		Collections.reverse(lr);
		content.put("httpCase", httpCase);
		content.put("entities", entities);
		content.put("headers", lh);
		content.put("urlParams", lu);
		content.put("nameValuePairs", ln);
		content.put("runBefores", lb);
		content.put("runAfters", lr);
		logger.info("-----------------------------------------------------------");
		for(String key:content.keySet()){
			logger.info("key :"+key);
			logger.info("value :"+content.get(key));
		}
		
		RunClient rc = new RunClient(content);
		Date rcStartTime = null;
		Date rcEndTime = null;
		try {
			rcStartTime=new Date();
			rc.run();
			rcEndTime=new Date();
		} catch (Exception e1) {
			rcEndTime=new Date();
			e1.printStackTrace();
		}
		double rcDurations = rcEndTime.getTime()-rcStartTime.getTime();
		String responseStr = rc.getResponse();
		httpCaseService.saveResponseAndResult(Integer.parseInt(caseId), rc.isExpected(), "");
		String msg = (rc.isExpected()?("状态: 运行成功\n运行时间: "+rcDurations/1000.0+" s\n"):("状态: 运行【失败!】\n运行时间: "+ rcDurations/1000.0 +" s\n"))+rc.getStrLog()+"$#$#$#"+responseStr;
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(msg);
		out.flush();
		out.close();
	}
	/**
	 * 
	* @Title: copyHttpNode
	* @Description: TODO(复制HTTP节点数据)
	* @param @throws Exception    参数
	* @return void    返回类型
	* @throws
	 */
	@Action(value = "copyHttpNode")
	public void copyHttpNode() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("UTF-8");
		String name = request.getParameter("name");
		String parentId = request.getParameter("parentId");
		String isParent = request.getParameter("isParent");
		String caseType = request.getParameter("caseType");
		String fromId = request.getParameter("fromId");
		logger.info("获取当前的父节点ID是：" + parentId);
		logger.info("获取当前的父节点NAME是：" + name);
		logger.info("获取当前节点是否父节点：" + isParent);
		logger.info("获取当前节点类型是：" + caseType);
		logger.info("复制来源ID是：" + fromId);

		CaseNode cn = new CaseNode();
		cn.setName(name);
		cn.setCaseType(caseType);
		cn.setIsParent(isParent.equals("true") ? true : false);
		cn.setOpen(false);
		if (parentId != null) {
			cn.setpId(parentId);
		}
		cn.setRemarks("");
		cn = caseService.save(cn);
		logger.info("存入的节点数据为：" + cn.toString());
		
		ArrayList<Header> lh = new ArrayList<Header>();
		ArrayList<UrlParam> lu = new ArrayList<UrlParam>();
		ArrayList<NameValuePair> ln = new ArrayList<NameValuePair>();
		ArrayList<RunBefore> lb = new ArrayList<RunBefore>();
		ArrayList<RunAfter> lr = new ArrayList<RunAfter>();
		Entities en = new Entities();
		HttpCase h = new HttpCase();
		
		int caseId = Integer.parseInt(fromId);
		lh = httpCaseService.getHeaders(caseId);
		lu = httpCaseService.getUrlParams(caseId);
		ln = httpCaseService.getNameValuePairs(caseId);
		lb = httpCaseService.getRunBefores(caseId);
		lr = httpCaseService.getRunAfters(caseId);
		h = httpCaseService.getHttpCase(caseId);
		en = httpCaseService.getEntities(caseId);
		
		logger.info("复制的httpCase是："+h!=null?h.toString():null);
		logger.info("复制的entities是："+en!=null?en.toString():null);
		int newId = cn.getId();
		
		if(lh!=null){
			ArrayList<Header> lhn = new ArrayList<Header>();
			for(Header header:lh){
				Header hnew = new Header();
				hnew.setCaseId(newId);
				hnew.setKey(header.getKey());
				hnew.setValue(header.getValue());
				lhn.add(hnew);
			}
			httpCaseService.saveHeaders(lhn);
		}
		if(lu!=null){
			ArrayList<UrlParam> lun = new ArrayList<UrlParam>();
			for (int i = 0; i < lu.size(); i++) {
				UrlParam u = new UrlParam();
				u.setCaseId(newId);
				u.setKey(lu.get(i).getKey());
				u.setValue(lu.get(i).getValue());
				lun.add(u);
			}
			httpCaseService.saveUrlParams(lun);
		}
		if(ln!=null){
			ArrayList<NameValuePair> lnn = new ArrayList<NameValuePair>();
			for(NameValuePair nvl : ln){
				NameValuePair nv = new NameValuePair();
				nv.setCaseId(newId);
				nv.setKey(nvl.getKey());
				nv.setValue(nvl.getValue());
				lnn.add(nv);
			}
			logger.info("修改nameValuePair");
			httpCaseService.saveNameValuePairs(lnn);
		}
		if(lb!=null){
			ArrayList<RunBefore> lbn = new ArrayList<RunBefore>();
			for(RunBefore rb :lb){
				RunBefore rbn = new RunBefore();
				rbn.setCaseId(newId);
				rbn.setClassPath(rb.getClassPath());
				rbn.setBeforeMethod(rb.getBeforeMethod());
				rbn.setBeforeMethodArgs(rb.getBeforeMethodArgs());
				lbn.add(rbn);
			}
			logger.info("修改runbefore");
			httpCaseService.saveRunBefores(lbn);
		}
		if(lr!=null){
			ArrayList<RunAfter> lrn = new ArrayList<RunAfter>();
			for(RunAfter ra:lr){
				RunAfter ran = new RunAfter();
				ran.setCaseId(newId);
				ran.setClassPath(ra.getClassPath());
				ran.setAfterMethod(ra.getAfterMethod());
				ran.setAfterMethodArgs(ra.getAfterMethodArgs());
				lrn.add(ran);
			}
			logger.info("修改runAfter");
			httpCaseService.saveRunAfters(lrn);
		}
		if(h!=null){
			HttpCase hn = new HttpCase();
			hn.setCaseId(newId);
			hn.setCaseType(h.getCaseType());
			hn.setCreateDateTime(new Date());
			hn.setHttpMethod(h.getHttpMethod());
			hn.setHttpUrl(h.getHttpUrl());
			User u = (User) ActionContext.getContext().getSession().get("user");
			hn.setOwer(u.getName());
			
			logger.info("修改后的httpCase是："+hn.toString());
			httpCaseService.saveHttpCase(hn);
		}
		if(en!=null){
			Entities enn = new Entities();
			enn.setCaseId(newId);
			enn.setData(en.getData());
			enn.setType(en.getType());
			logger.info("修改后的entities是："+enn.toString());
			httpCaseService.saveEntities(enn);
		}
		
		String msg = newId+"";
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(msg);
		out.flush();
		out.close();
	}
	
}
